//
//  GoodsSortVC.m
//  reSearchDemo
//
//  Created by 云库 on 15/9/18.
//  Copyright (c) 2015年 Kiwaro. All rights reserved.
//

#import "GoodsSortVC.h"
#import "MJExtension.h"
#import "MBProgressHUD.h"
#import "GoodsSort.h"
#import "GoodsSortTableViewCell.h"
#import "UIView+Category.h"
#import "GoodsDetailVC.h"
#import "GoodsDetail.h"
#import "MJRefresh.h"
#import "DOPDropDownMenu.h"
#import "GoodsClass.h"
#import "BrandList.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "NearbyShopsClass.h"

@interface GoodsSortVC ()<UITableViewDelegate,UITableViewDataSource,DOPDropDownMenuDataSource,DOPDropDownMenuDelegate,MKMapViewDelegate,CLLocationManagerDelegate> {
    CLLocationManager *_locationManager;   /**< 位置对象  */
    MKMapView *_mapView;      /**< 地图 */
    CLLocationCoordinate2D CurrentCoord;    /**< 当前定位的经纬度  */
    BOOL isPerform;                  /**< 判断分类是否刷新    */
    NSMutableArray *nearModel;       /**< 附近数据   */
    NSMutableArray *OneHundredMetersModel;   /**< 附近一百米数据 */
    NSMutableArray *FiveHundredMetersModel;  /**< 附近五百米数据 */
    
    DOPDropDownMenu *DOPmenu;   /**< 菜单 */
    int MenuCount;           /**< 当前选中菜单 0-附近 1-100米 2-500米 默认为0 */
    NSArray *TypeIdArr;      /**< 商品类型ID的数据 */
    
    BOOL isDataSource;       /**< 判断数据源是否为空 */
}


@property (nonatomic, strong) NSArray *classifys;
@property (nonatomic, strong) NSArray *cates;
@property (nonatomic, strong) NSArray *movices;
@property (nonatomic, strong) NSArray *hostels;
@property (nonatomic, strong) NSArray *areas;
@property (nonatomic, strong) NSArray *sorts;

//以上假数据



@property (strong, nonatomic) UIView *headerView;
/** tableView*/
@property (strong, nonatomic) UITableView *tableView;


@property (strong, nonatomic) MBProgressHUD *hub;
/** 类数据模型*/
@property (strong, nonatomic) NSMutableArray *dealsArr;

/** 团购订单 pageno参数*/
@property (nonatomic,assign) int pageno;

/** 附近*/
@property (strong, nonatomic) NSArray *nearArr;
/** 分类*/
//@property (strong, nonatomic) NSArray *sortArr;
/** 排序*/
@property (strong, nonatomic) NSArray *rankArr;
/** 筛选*/
//@property (strong, nonatomic) NSArray *chooseArr;

/** 本地已经从网络保存的分类数据*/
@property (strong, nonatomic) NSArray *goodsSortArr;

@end



@implementation GoodsSortVC

/**
 * 初始化
 */
- (NSMutableArray *)dealsArr{
    if (!_dealsArr) {
        _dealsArr = [NSMutableArray array];
    }
    return  _dealsArr;
}


- (NSArray *)goodsSortArr{
    if (!_goodsSortArr) {
        _goodsSortArr = [NSMutableArray array];
    }
    return  _goodsSortArr;
}

- (void)viewWillAppear:(BOOL)animated{
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    MenuCount = 0;
    
    //创建地图
    [self loadMapView];
    
    //获取分类菜单
    [self getSortPlist];
    
    // 数据
    self.classifys = @[@"美食",@"今日新单",@"电影",@"酒店"];
    self.cates = @[@"自助餐",@"快餐",@"火锅",@"日韩料理",@"西餐",@"烧烤小吃"];
    self.movices = @[@"内地剧",@"港台剧",@"英美剧"];
    self.hostels = @[@"经济酒店",@"商务酒店",@"连锁酒店",@"度假酒店",@"公寓酒店"];
    self.areas = @[@"全城",@"芙蓉区",@"雨花区",@"天心区",@"开福区",@"岳麓区"];
    self.sorts = @[@"默认排序",@"离我最近",@"好评优先",@"人气优先",@"最新发布"];

    
    
    self.nearArr = @[@"附近",@"500米",@"1000米"];
    self.rankArr = @[@"分类",@"美食",@"居家",@"娱乐",@"电影"];
    
    
    TypeIdArr = @[@32,@82,@83,@37,@34,@84,];
    
    //顶部菜单按钮视图
    [self setUpHeaderView];
    
    //tableView
    [self setUpTableView];
    //刷新控件（创建tableView后才刷新）
    //下拉刷新
    [self setupDownRefresh];
    //上拉加载
    [self setupUpRefresh];
    
        /** 设置右侧导航栏*/
    [self setRightBarButtonImage:LOADIMAGE(@"actionbar_search_icon") highlightedImage:nil selector:@selector(search)];
    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
    back.title = @"";
    self.navigationItem.backBarButtonItem = back;
    
    isPerform = YES;
    isDataSource = YES;
    self.hub = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hub];
    
}
#pragma mark --百度地图定位--
- (void)loadMapView {
    CGRect rect=[UIScreen mainScreen].bounds;
    _mapView=[[MKMapView alloc]initWithFrame:rect];
    [self.view addSubview:_mapView];
    //设置代理
    _mapView.delegate=self;
    
    //请求定位服务
    _locationManager=[[CLLocationManager alloc]init];
    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
        [_locationManager requestWhenInUseAuthorization];
    }
    
    //用户位置追踪(用户位置追踪用于标记用户当前位置，此时会调用定位服务)
    _mapView.userTrackingMode=MKUserTrackingModeFollow;
    
    //设置地图类型
    _mapView.mapType=MKMapTypeStandard;
    
    //隐藏地图
    _mapView.hidden = YES;

}

#pragma mark -
#pragma mark --下拉刷新--
/** 下拉刷新*/
- (void)setupDownRefresh
{
    // 1.添加刷新控件
    [self.tableView addHeaderWithTarget:self action:@selector(loadNewDeals)];
    
    // 2.进入刷新状态(下拉刷新)
    [self.tableView headerBeginRefreshing];
    
}
#pragma mark --上拉加载--
/** 上拉加载*/
- (void)setupUpRefresh
{
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreDeals)];
}

#pragma mark --加载最新数据--
- (void)loadNewDeals{
    self.pageno = 1;
    [self loadDataFromServer];
}

#pragma mark --加载更多数据--
- (void)loadMoreDeals{
    
    //设置其他参数
    self.pageno++;
    //重新发送请求
    [self loadDataFromServer];
}

#pragma mark --加载数据源 --
/** 获取数据*/
- (void)loadDataFromServer{
    DLog(@"typeId = %@",self.typeId);
    self.hub.labelText = @"正在拼命加载中....";
    [self.hub show:YES];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //根据不同ID获取
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"pageno"] = @(self.pageno);
    param[@"typeId"] = self.typeId;
    NSString *path = [NSString stringWithFormat:@"%@%@",SHOPER,@"html/agoods/search.do"];
    [manager GET:path parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        DLog(@"responseObject = %@",responseObject);
        
        [self.hub hide:YES];
        
        NSArray *array = [GoodsSort objectArrayWithKeyValuesArray:responseObject[@"data"]];
        if (array.count) {
            isDataSource = YES;
        }else {
            isDataSource = NO;
        }
        //没有上拉加载
        if (self.pageno == 1) {
            //将之前旧的数据清空
            [self.dealsArr removeAllObjects];
        }
        
        [self.dealsArr addObjectsFromArray:array];
        
        [self.tableView reloadData];
        
        
        // 结束下拉刷新
        [self.tableView headerEndRefreshing];
        // 结束刷新刷新
//        [self.tableView footerEndRefreshing];
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             //结束刷新
             [self.tableView headerEndRefreshing];
             [self.tableView footerEndRefreshing];
             DLog(@"网络不佳或请求错误...%@",self.class);
             [self.hub hide:YES afterDelay:2];
             isDataSource = NO;
             [self.tableView reloadData];
         }];
    
}

/** 顶部菜单按钮视图*/
- (void)setUpHeaderView{
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.width, 44)];
    self.headerView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.headerView];
    
    //选择菜单
    DOPmenu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:43];
    DOPmenu.dataSource = self;
    DOPmenu.delegate = self;
    [self.view addSubview:DOPmenu];

}

#pragma mark --创建tableview--
- (void)setUpTableView{
    
    //2.创建table view
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.headerView.y+self.headerView.height, self.view.width, self.view.height-self.headerView.height-64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.tableView];
    
}

#pragma mark --获取分类信息
- (void)getSortPlist{
    nearModel = [NSMutableArray array];
    NSDictionary *dic = @{@"lon":@"104",@"lat":@"31",@"dist":@"100",@"pageno":@"1",@"type":@"2"};
    NSDictionary *dic1 = @{@"lon":@"105.399",@"lat":@"31.2279",@"dist":@"100",@"pageno":@"1",@"type":@"2"};
    NSDictionary *dic2 = @{@"lon":@"113.2852452",@"lat":@"23.2116398",@"dist":@"1000000",@"pageno":@"1",@"type":@"2"};
    NSArray *arrDic = @[dic,dic1,dic2];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    for (int i = 0; i<arrDic.count; i++) {
        NSString *path = [NSString stringWithFormat:@"%@%@",SHOPER,@"html/ashop/nearshop.do"];
        [manager POST:path parameters:arrDic[i] success:^(AFHTTPRequestOperation * operation, id obj) {
            DLog(@"obj = %@",obj);
            NSArray *arr = obj[@"data"];
            NSMutableArray *Data = [NSMutableArray array];
            for (NSDictionary *dic in arr) {
                NearbyShopsClass *model = [[NearbyShopsClass alloc] initWithDictionary:dic];
                [Data addObject:model];
            }
            [nearModel addObject:Data];
            //手动调用代理方法
            [DOPmenu selectDefalutIndexPath];
        } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
            DLog(@"error = %@",error);
        }];
    }
    
    
    //该路径取决于MoreSort的路径
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"sort.plist"];
    
    NSDictionary *responseObject = [NSDictionary dictionaryWithContentsOfFile:filePath];
    //总的分类
    self.goodsSortArr = [GoodsClass objectArrayWithKeyValuesArray:responseObject[@"DATA"]];
    
}
/**
 *搜索框按钮
 */
- (void)search{
    DLog(@"搜索按钮");
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 地图控件代理方法
//然后通过MKMapView的委托方法来获取准确的经纬度:
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    CLLocationCoordinate2D coord = [userLocation coordinate];
    CurrentCoord = [userLocation coordinate];
    DLog(@"经度:%f,纬度:%f",coord.latitude,coord.longitude);
    if (isPerform) {
        isPerform = NO;
        //获取分类列表
//        [self getSortPlist];
    }
}

#pragma mark -
#pragma mark -- menuDelegate --
//返回 menu 有多少列 ，默认1列
- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu {
    return 2;
}
//返回 menu 第column列 每行title
- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath {
    switch (indexPath.column) {
        case 0:
            if (indexPath.row == 0) {
                return @"附近";
            }else {
               return nil;
            }
            break;
            //主分类
        case 1:
            if (indexPath.row == 0) {
                return @"服装";
            }else {
                return nil;
            }
            break;
            
        default:
            return nil;
            break;
    }
}
//返回 menu 第column列有多少行
- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column {
    if (column==0) {
        return 1;
    }else {//总分类个数
//        NSArray *arr = nearModel[MenuCount];
//    return arr.count;
        return 1;
    }
   
}
// 当有column列 row 行 返回有多少个item ，如果>0，说明有二级列表 ，=0 没有二级列表
- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfItemsInRow:(NSInteger)row column:(NSInteger)column
{
    if (column == 0) {
        return self.nearArr.count;
    }else {
        if (!nearModel.count) {
            return 0;
        }
        NSArray *arr = nearModel[MenuCount];
        return arr.count;
    }
}
// 当有column列 row 行 item项 title
- (NSString *)menu:(DOPDropDownMenu *)menu titleForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (!nearModel.count) {
        return nil;
    }
    NSArray *arr = nearModel[MenuCount];
    NearbyShopsClass *subSort = arr[indexPath.item];
    
    if (indexPath.column == 0) {
        return self.nearArr[indexPath.item];
    }else {
        return subSort.name;
    }
    
}
//点击代理，点击了第column 第row 或者item项，如果 item >=0
- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath {
    DLog(@"column:%li row:%li", (long)indexPath.column, (long)indexPath.row);
    DLog(@"%@",[menu titleForRowAtIndexPath:indexPath]);
   // NSString *title = [menu titleForRowAtIndexPath:indexPath];
    DLog(@"row = %ld",(long)indexPath.row);
    DLog(@"itme = %ld",(long)indexPath.item);
    if (indexPath.column == 0 && indexPath.item >= 0) {
        MenuCount = (int)indexPath.item;
    }else {
        if (indexPath.item >= 0) {
            self.typeId = TypeIdArr[indexPath.item];
            //重新获取数据
            [self loadDataFromServer];
        }
    }
}

#pragma mark -- tableView代理方法 --
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dealsArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"GoodsSortTableViewCell";
    GoodsSortTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell = [[[NSBundle mainBundle]loadNibNamed:@"GoodsSortTableViewCell" owner:self options:nil]lastObject];
    }
    GoodsSort * goods = self.dealsArr[indexPath.row];
    cell.deals = goods;
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //弹出详细商品视图
    GoodsDetailVC *goodsDetailVC = [[GoodsDetailVC alloc] init];
    //取出对应的参数传递
    GoodsSort * goods = self.dealsArr[indexPath.row];
    goodsDetailVC.goodId = goods.goodId;//以此查看详情
    goodsDetailVC.shopName = goods.shopname;//title
    goodsDetailVC.shop_id = goods.shopid;//以此进入商家平台
    
    [self pushViewController:goodsDetailVC];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

//头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView;
    if (!isDataSource) {
        headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_tableView.frame), CGRectGetHeight(_tableView.frame))];
        headView.backgroundColor = [UIColor lightGrayColor];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        label.center = headView.center;
        label.text = @"无内容!";
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:25];
        [headView addSubview:label];
        
        return headView;
    }else {
        return nil;
    }
}
//设置表头的高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (!isDataSource) {
        return CGRectGetHeight(_tableView.frame);
    }else {
        return 0;
    }
}

@end
